<template>
	<div>
		<div v-show="flag" style="border: 1px solid red">
			<Emotion @emotion="getEmotion" />
		</div>
		<div id="test" ref="box" contenteditable="true" style="height: 200px; width: 400px; border: 1px solid red" @paste="pastefunction" />
		<el-button type="primary" @click="openFace">表情</el-button>
	</div>
</template>

<script>
import axios from "axios";
export default {
	components: {
		Emotion: () => import("@/components/Emotion"),
	},
	data() {
		return {
			src: "",
			flag: false,
		};
	},
	mounted() {},
	methods: {
		openFace() {
			this.flag = true;
		},
		getEmotion(el) {
			// let selection = window.getSelection();
			// selection.anchorNode.splitText(selection.anchorNode.after(el))
			document.execCommand("insertHTML", false, el); // 返回值boolean代表是否插入成功 //不兼容兼容ie，优化思路通过光标分割进行插入
		},
		// 将base64转换为blob
		dataURLtoBlob(dataurl) {
			let arr = dataurl.split(",");
			let mime = arr[0].match(/:(.*?);/)[1];
			let bstr = atob(arr[1]);
			let n = bstr.length;
			let u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			let blob = new Blob([u8arr], { type: mime });
			//  return new File([blob], filename, {type:mime});//base64转换为file ie不兼容
			return this.blobToFile(blob, "123");
		},
		// 将blob转换为file 貌似也没转换成功
		blobToFile(theBlob, fileName) {
			theBlob.lastModifiedDate = new Date();
			theBlob.name = fileName;
			return theBlob;
		},
		pastefunction(event) {
			let text;
			if (event.clipboardData || event.originalEvent) {
				event.preventDefault();
				let clipboardData = event.clipboardData || event.originalEvent.clipboardData;
				// 兼容chorme或hotfire
				let items = clipboardData.items;
				for (let i = 0, len = items.length; i < len; i++) {
					console.log(items[i].type);
					if (items[i].type.indexOf("image") !== -1) {
						let blob = items[i].getAsFile(); // 此方法只是living standard firefox ie11 并不支持
						this.upLoad(blob);
						// var reader = new FileReader();
						// reader.onload = (event) => {
						//   //  reader.result//图片的Base64编码字符串
						//   //可以在这里写上传逻辑 直接将base64编码的字符串上传
						//   console.log(blob);
						// }
						// reader.readAsDataURL(blob);
						break;
					} else if (items[i].type.indexOf("text") !== -1) {
						text = clipboardData.getData("text/plain"); // text/html
						console.log(text);
						document.execCommand("insertText", false, text);
						break;
					}
				}
			} else {
				// for ie11
				text = window.clipboardData.getData("text") || "";
				if (text !== "") {
					// 获取粘贴文本
					event.preventDefault ? event.preventDefault() : (event.returnValue = false);
					if (window.getSelection) {
						// 针对于ie11 10 9 safari
						let newNode = document.createElement("span");
						newNode.innerHTML = text;
						window.getSelection().getRangeAt(0).insertNode(newNode);
					} else {
						// 兼容ie10 9 8 7 6 5
						document.selection.createRange().pasteHTML(text);
					}
				} else {
					// 获取文件还没完善
					setTimeout(async () => {
						let imgList = document.querySelectorAll("#test img");
						for (let i = 0, len = imgList.length; i < len; i++) {
							// console.log(imgList[i]);//base64格式
							if (imgList[i].className.indexOf("my_img") == -1) {
								// let formDate = new FormData();
								let file = this.dataURLtoBlob(imgList[i].src, "123");
								this.upLoad(file);
							}
						}
					}, 1);
				}
			}
		},
		// 上传
		async upLoad(file) {
			const url =
				process.env.NODE_ENV === "production"
					? "http://121.36.2.1:22222/admin/guest/file/uploadChatFile?creatorId=1002&customerId=1002"
					: "/upLoadFile";
			const FormDatas = new FormData();
			FormDatas.append("file", file.file || file);
			const { data } = await axios.post(url, FormDatas, {});
			document.execCommand("insertHtml", false, `<img src="${data.data.path}" alt="" style="width:80px;height:80px" >`);
		},
	},
};
</script>

<style lang="scss">
#test {
	line-height: 24px;
	img {
		vertical-align: middle;
	}
}
</style>
